package com.papercutting.platform.controller;

import com.papercutting.platform.common.Result;
import com.papercutting.platform.entity.News;
import com.papercutting.platform.service.NewsService;
import com.papercutting.platform.util.ImageUrlUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 活动资讯控制器
 */
@RestController
@RequestMapping("/api/news")
@RequiredArgsConstructor
public class NewsController {
    
    private final NewsService newsService;
    private final ImageUrlUtil imageUrlUtil;
    
    /**
     * 获取资讯列表
     */
    @GetMapping("/list")
    public Result<Map<String, Object>> getNewsList(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) Integer type,
            @RequestParam(required = false) String keyword,
            @RequestParam(defaultValue = "createTime") String orderBy) {
        
        // 创建分页对象
        Sort sort = Sort.by(Sort.Direction.DESC, orderBy);
        Pageable pageable = PageRequest.of(page - 1, size, sort);
        
        // 查询数据
        Page<News> newsPage = newsService.findNewsList(type, keyword, null, pageable);
        
        // 处理图片URL
        newsPage.getContent().forEach(news -> {
            if (news.getCoverImage() != null) {
                news.setCoverImage(imageUrlUtil.processImageUrl(news.getCoverImage()));
            }
        });
        
        // 构造返回结果
        Map<String, Object> result = new HashMap<>();
        result.put("list", newsPage.getContent());
        result.put("total", newsPage.getTotalElements());
        result.put("page", page);
        result.put("size", size);
        result.put("totalPages", newsPage.getTotalPages());
        
        return Result.success(result);
    }
    
    /**
     * 获取资讯详情
     */
    @GetMapping("/{id}")
    public Result<News> getNewsDetail(@PathVariable Long id) {
        News news = newsService.findById(id);
        if (news == null) {
            return Result.error(404, "资讯不存在");
        }
        
        // 处理图片URL
        if (news.getCoverImage() != null) {
            news.setCoverImage(imageUrlUtil.processImageUrl(news.getCoverImage()));
        }
        
        // 增加浏览量
        newsService.increaseViewCount(id);
        
        return Result.success(news);
    }
    
    /**
     * 获取推荐资讯
     */
    @GetMapping("/recommend")
    public Result<List<News>> getRecommendList(@RequestParam(defaultValue = "5") Integer limit) {
        List<News> recommendList = newsService.findByIsRecommend(true);
        // 处理图片URL
        recommendList.forEach(news -> {
            if (news.getCoverImage() != null) {
                news.setCoverImage(imageUrlUtil.processImageUrl(news.getCoverImage()));
            }
        });
        return Result.success(recommendList.stream().limit(limit).toList());
    }
    
    /**
     * 获取置顶资讯
     */
    @GetMapping("/top")
    public Result<List<News>> getTopList(@RequestParam(defaultValue = "5") Integer limit) {
        List<News> topList = newsService.findByIsTop(true);
        // 处理图片URL
        topList.forEach(news -> {
            if (news.getCoverImage() != null) {
                news.setCoverImage(imageUrlUtil.processImageUrl(news.getCoverImage()));
            }
        });
        return Result.success(topList.stream().limit(limit).toList());
    }
    
    /**
     * 搜索资讯
     */
    @GetMapping("/search")
    public Result<Map<String, Object>> searchNews(
            @RequestParam String keyword,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size) {
        
        Pageable pageable = PageRequest.of(page - 1, size);
        Page<News> newsPage = newsService.findNewsList(null, keyword, null, pageable);
        
        Map<String, Object> result = new HashMap<>();
        result.put("list", newsPage.getContent());
        result.put("total", newsPage.getTotalElements());
        result.put("page", page);
        result.put("size", size);
        result.put("totalPages", newsPage.getTotalPages());
        
        return Result.success(result);
    }
    
    /**
     * 获取类型统计
     */
    @GetMapping("/type-stats")
    public Result<List<Map<String, Object>>> getTypeStats() {
        // 这里应该实现类型统计的逻辑
        return Result.success(List.of());
    }
}